package bb.lanxing.lib.devices.sprint.sync;

import bb.lanxing.lib.devices.core.sync.DeviceFile;
import bb.lanxing.lib.devices.core.sync.DeviceFileStatus;
import bb.lanxing.lib.devices.core.sync.FitDeviceFile;
import bb.lanxing.lib.devices.sprint.Command;
import bb.lanxing.lib.devices.sprint.Commands;
import bb.lanxing.lib.devices.sprint.SprintFile;
import bb.lanxing.lib.devices.sprint.SprintListener;
import bb.lanxing.lib.devices.sprint.XossDeviceController;
import bb.lanxing.lib.devices.sprint.utils.DeviceControllerHelper;
import bb.lanxing.lib.devices.sprint.utils.SprintFileHelper;
import bb.lanxing.lib.devices.sync.AbstractFitSyncManager;
import bb.lanxing.lib.devices.sync.FitTrans;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public abstract class AbstractSprintHistorySyncManager extends AbstractFitSyncManager implements SprintListener {
    private String address;
    private XossDeviceController controller;
    private String workDir;

    @Override
    public boolean resync(DeviceFile deviceFile) {
        return false;
    }

    @Override
    public boolean sync(String str) {
        return false;
    }

    @Override
    protected void uploadToServer(DeviceFile deviceFile) {
    }

    public AbstractSprintHistorySyncManager(String str, String str2) {
        this.address = str;
        this.workDir = str2;
        XossDeviceController xossDeviceController = DeviceControllerHelper.getXossDeviceController(str);
        this.controller = xossDeviceController;
        xossDeviceController.registerXossDeviceListener(this);
    }

    public XossDeviceController getController() {
        if (this.controller == null) {
            XossDeviceController xossDeviceController = DeviceControllerHelper.getXossDeviceController(this.address);
            this.controller = xossDeviceController;
            xossDeviceController.registerXossDeviceListener(this);
        }
        return this.controller;
    }

    @Override
    public void readFileList() {
        File file = new File(this.workDir, SprintFileHelper.FILE_LIST);
        if (file.exists()) {
            List<DeviceFile> convertToDeviceFiles = convertToDeviceFiles(file.getAbsolutePath());
            if (getDeviceFiles() == null || getDeviceFiles().size() != file.length()) {
                getController().getFileList();
                return;
            }
            setDeviceFiles(convertToDeviceFiles);
            notifyDeviceFiles(convertToDeviceFiles);
            return;
        }
        getController().getFileList();
    }

    private List<DeviceFile> convertToDeviceFiles(String str) {
        Date date;
        File file = new File(str);
        List<SprintFile> parseFileList = SprintFileHelper.parseFileList(file.getParent(), file.getAbsolutePath());
        if (parseFileList != null) {
            ArrayList arrayList = new ArrayList();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
            for (SprintFile sprintFile : parseFileList) {
                try {
                    String fileName = sprintFile.getFileName();
                    int lastIndexOf = fileName.lastIndexOf(".");
                    if (lastIndexOf != -1) {
                        fileName = fileName.substring(0, lastIndexOf);
                    }
                    date = simpleDateFormat.parse(fileName);
                } catch (ParseException unused) {
                    date = null;
                }
                FitDeviceFile fitDeviceFile = new FitDeviceFile();
                fitDeviceFile.setId(generateSeq());
                fitDeviceFile.setSize(sprintFile.getSize());
                fitDeviceFile.setStartTime(date != null ? date.getTime() : 0L);
                fitDeviceFile.setName(sprintFile.getFileName());
                fitDeviceFile.setPath(sprintFile.getPath());
                arrayList.add(fitDeviceFile);
            }
            Collections.sort(arrayList, new Comparator<DeviceFile>() {
                @Override
                public int compare(DeviceFile deviceFile, DeviceFile deviceFile2) {
                    return ((int) (((FitDeviceFile) deviceFile2).getStartTime() / 1000)) - ((int) (((FitDeviceFile) deviceFile).getStartTime() / 1000));
                }
            });
            return arrayList;
        }
        return null;
    }

    private boolean removeLine(String str) {
        File file = new File(this.workDir, SprintFileHelper.FILE_LIST);
        File file2 = new File(this.workDir, SprintFileHelper.FILE_LIST_TMP);
        if (!file.exists()) {
            return false;
        }
        if (!file2.exists()) {
            try {
                file2.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file2));
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine != null) {
                    if (!readLine.trim().contains(str)) {
                        bufferedWriter.write(readLine + System.getProperty("line.separator"));
                    }
                } else {
                    bufferedWriter.close();
                    bufferedReader.close();
                    return file2.renameTo(file);
                }
            }
        } catch (IOException e2) {
            e2.printStackTrace();
            return false;
        }
    }

    @Override
    public void delete(long j) {
        DeviceFile deviceFileById = getDeviceFileById(j);
        if (deviceFileById == null) {
            return;
        }
        getController().delete(deviceFileById.getName());
    }

    @Override
    public void deleteAll() {
        getController().deleteAll();
    }

    @Override
    public void abort() {
        getController().abort();
    }

    @Override
    public void abortAll() {
        abort();
        clearPendingFiles();
    }

    @Override
    public void release() {
        super.release();
        getController().unregisterXossDeviceListener(this);
        this.controller = null;
    }

    @Override
    protected boolean syncImpl(DeviceFile deviceFile) {
        getController().getFile(deviceFile.getName());
        return true;
    }

    @Override
    public String getPath(long j) {
        DeviceFile deviceFileById = getDeviceFileById(j);
        if (deviceFileById != null) {
            return deviceFileById.getPath();
        }
        return null;
    }

    public DeviceFile getDeviceFileByPath(String str) {
        List<DeviceFile> deviceFiles = getDeviceFiles();
        if (deviceFiles == null || deviceFiles.isEmpty() || str == null) {
            return null;
        }
        return getDeviceFileByName(new File(str).getName());
    }

    @Override
    public void onProgressUpdate(Command command, float f) {
        DeviceFile currentDeviceFile = getCurrentDeviceFile();
        if (currentDeviceFile != null && command.getCmd() == 5) {
            notifyProgressUpdate(currentDeviceFile, f);
        }
    }

    @Override
    public void onCmdStatus(Command command, int i, byte[] bArr) {
        DeviceFile deviceFileByName;
        String parseFileName = Commands.parseFileName(command);
        byte cmd = command != null ? command.getCmd() : (byte) 1;
        if (i == 3) {
            notifyDeviceStatus(cmd);
        }
        if (SprintFileHelper.isFileList(parseFileName)) {
            if (i == 0) {
                return;
            }
            notifyDeviceFiles(null);
        } else if (cmd == 5) {
            DeviceFile deviceFileByName2 = getDeviceFileByName(parseFileName);
            if (deviceFileByName2 == null || i == 0) {
                return;
            }
            notifySyncStatus(deviceFileByName2, DeviceFileStatus.STATUS_SYNC_FAIL.getStatus());
        } else if (cmd != 13) {
            if (cmd != 15 || (deviceFileByName = getDeviceFileByName(parseFileName)) == null) {
                return;
            }
            if (i == 0) {
                notifySyncStatus(deviceFileByName, DeviceFileStatus.STATUS_DELETED_ALL.getStatus());
            } else {
                notifySyncStatus(deviceFileByName, DeviceFileStatus.STATUS_DELETE_ALL_FAIL.getStatus());
            }
        } else {
            DeviceFile deviceFileByName3 = getDeviceFileByName(parseFileName);
            if (deviceFileByName3 == null) {
                return;
            }
            if (i == 0) {
                removeById(deviceFileByName3.getId());
                removeLine(deviceFileByName3.getName());
                notifySyncStatus(deviceFileByName3, DeviceFileStatus.STATUS_DELETED.getStatus());
                return;
            }
            notifySyncStatus(deviceFileByName3, DeviceFileStatus.STATUS_DELETE_FAIL.getStatus());
        }
    }

    @Override
    public void onFileReceived(String str) {
        if (SprintFileHelper.isFileList(str)) {
            List<DeviceFile> convertToDeviceFiles = convertToDeviceFiles(str);
            setDeviceFiles(convertToDeviceFiles);
            notifyDeviceFiles(convertToDeviceFiles);
            return;
        }
        FitTrans fitTrans = FitTrans.get();
        DeviceFile deviceFileByPath = getDeviceFileByPath(str);
        if (deviceFileByPath == null) {
            return;
        }
        fitTrans.setId(deviceFileByPath.getId());
        fitTrans.setPath(str);
        onFitReceived(fitTrans);
    }

    @Override
    public int getSyncState(long j) {
        int syncState = super.getSyncState(j);
        if (!isSynchronised(j) && DeviceFileStatus.STATUS_SYNCED.getStatus() == syncState) {
            syncState = DeviceFileStatus.STATUS_NONE.getStatus();
            DeviceFile deviceFileById = getDeviceFileById(j);
            if (deviceFileById != null) {
                notifySyncStatus(deviceFileById, syncState);
            }
        }
        return syncState;
    }
}
